<template>
  <div class="courses">
    <!-- 导航栏 -->
    <NavBar
      title="课程"
      :left-arrow="false"
      class="courses__navbar"
    >
      <template #right>
        <van-icon name="search" size="18" @click="onSearch" />
      </template>
    </NavBar>

    <!-- 搜索栏 -->
    <div v-if="showSearch" class="courses__search">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索课程"
        @search="onSearchSubmit"
        @cancel="onSearchCancel"
        show-action
      />
    </div>

    <!-- 分类筛选 -->
    <div class="courses__filter">
      <van-tabs v-model:active="activeCategory" @change="onCategoryChange" sticky>
        <van-tab title="全部" name="all" />
        <van-tab title="前端开发" name="frontend" />
        <van-tab title="后端开发" name="backend" />
        <van-tab title="移动开发" name="mobile" />
        <van-tab title="数据库" name="database" />
        <van-tab title="人工智能" name="ai" />
      </van-tabs>
    </div>

    <!-- 排序和筛选 -->
    <div class="courses__toolbar">
      <div class="courses__sort">
        <van-dropdown-menu>
          <van-dropdown-item v-model="sortType" :options="sortOptions" />
          <van-dropdown-item v-model="filterLevel" :options="levelOptions" title="难度" />
          <van-dropdown-item v-model="filterPrice" :options="priceOptions" title="价格" />
        </van-dropdown-menu>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="courses__content">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="courses__list">
            <div
              v-for="course in courseList"
              :key="course.id"
              class="course-card"
              @click="onCourseClick(course)"
            >
              <!-- 课程封面 -->
              <div class="course-card__cover">
                <img :src="course.cover" :alt="course.title" />
                <div class="course-card__badge">
                  <span v-if="course.isFree" class="course-card__free">免费</span>
                  <span v-else class="course-card__price">¥{{ course.price }}</span>
                </div>
                <div class="course-card__duration">{{ course.duration }}</div>
              </div>
              
              <!-- 课程信息 -->
              <div class="course-card__content">
                <h3 class="course-card__title">{{ course.title }}</h3>
                <p class="course-card__desc">{{ course.description }}</p>
                
                <!-- 课程标签 -->
                <div class="course-card__tags">
                  <span class="course-card__tag course-card__tag--level">{{ course.level }}</span>
                  <span class="course-card__tag course-card__tag--category">{{ course.category }}</span>
                </div>
                
                <!-- 课程统计 -->
                <div class="course-card__stats">
                  <div class="course-card__stat">
                    <van-icon name="user-o" size="12" />
                    <span>{{ course.studentCount }}人学习</span>
                  </div>
                  <div class="course-card__stat">
                    <van-icon name="star" size="12" />
                    <span>{{ course.rating }}</span>
                  </div>
                  <div class="course-card__stat">
                    <van-icon name="clock-o" size="12" />
                    <span>{{ course.updateTime }}</span>
                  </div>
                </div>
                
                <!-- 讲师信息 -->
                <div class="course-card__teacher">
                  <img :src="course.teacher.avatar" :alt="course.teacher.name" />
                  <span>{{ course.teacher.name }}</span>
                </div>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 底部标签栏 -->
    <TabBar />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import NavBar from '@/components/common/NavBar.vue'
import TabBar from '@/components/common/TabBar.vue'

const router = useRouter()

// 搜索相关
const showSearch = ref(false)
const searchKeyword = ref('')

// 分类筛选
const activeCategory = ref('all')

// 排序和筛选
const sortType = ref('default')
const filterLevel = ref('all')
const filterPrice = ref('all')

// 排序选项
const sortOptions = [
  { text: '默认排序', value: 'default' },
  { text: '最新发布', value: 'newest' },
  { text: '最多学习', value: 'popular' },
  { text: '评分最高', value: 'rating' },
  { text: '价格最低', value: 'price_asc' },
  { text: '价格最高', value: 'price_desc' }
]

// 难度选项
const levelOptions = [
  { text: '全部难度', value: 'all' },
  { text: '入门', value: 'beginner' },
  { text: '进阶', value: 'intermediate' },
  { text: '高级', value: 'advanced' }
]

// 价格选项
const priceOptions = [
  { text: '全部价格', value: 'all' },
  { text: '免费', value: 'free' },
  { text: '0-100元', value: '0-100' },
  { text: '100-500元', value: '100-500' },
  { text: '500元以上', value: '500+' }
]

// 列表相关
const courseList = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const page = ref(1)
const pageSize = 10

// 模拟课程数据
const mockCourses = [
  {
    id: 1,
    title: 'Vue.js 3.0 从入门到精通',
    description: '全面学习Vue.js 3.0新特性，包括Composition API、Teleport等',
    cover: 'https://picsum.photos/300/200?random=1',
    category: '前端开发',
    level: '进阶',
    price: 299,
    isFree: false,
    duration: '20小时',
    studentCount: 1234,
    rating: 4.8,
    updateTime: '2024-01-15',
    teacher: {
      name: '张老师',
      avatar: 'https://picsum.photos/40/40?random=101'
    }
  },
  {
    id: 2,
    title: 'React Hooks 实战教程',
    description: '深入理解React Hooks，掌握函数式组件开发',
    cover: 'https://picsum.photos/300/200?random=2',
    category: '前端开发',
    level: '高级',
    price: 399,
    isFree: false,
    duration: '15小时',
    studentCount: 856,
    rating: 4.9,
    updateTime: '2024-01-10',
    teacher: {
      name: '李老师',
      avatar: 'https://picsum.photos/40/40?random=102'
    }
  },
  {
    id: 3,
    title: 'JavaScript 基础入门',
    description: '零基础学习JavaScript，掌握前端开发基础',
    cover: 'https://picsum.photos/300/200?random=3',
    category: '前端开发',
    level: '入门',
    price: 0,
    isFree: true,
    duration: '25小时',
    studentCount: 3456,
    rating: 4.7,
    updateTime: '2024-01-08',
    teacher: {
      name: '王老师',
      avatar: 'https://picsum.photos/40/40?random=103'
    }
  },
  {
    id: 4,
    title: 'Node.js 后端开发实战',
    description: '使用Node.js构建高性能后端服务',
    cover: 'https://picsum.photos/300/200?random=4',
    category: '后端开发',
    level: '进阶',
    price: 499,
    isFree: false,
    duration: '30小时',
    studentCount: 678,
    rating: 4.6,
    updateTime: '2024-01-05',
    teacher: {
      name: '赵老师',
      avatar: 'https://picsum.photos/40/40?random=104'
    }
  },
  {
    id: 5,
    title: 'Flutter 移动应用开发',
    description: '跨平台移动应用开发，一套代码多端运行',
    cover: 'https://picsum.photos/300/200?random=5',
    category: '移动开发',
    level: '进阶',
    price: 599,
    isFree: false,
    duration: '35小时',
    studentCount: 432,
    rating: 4.8,
    updateTime: '2024-01-03',
    teacher: {
      name: '钱老师',
      avatar: 'https://picsum.photos/40/40?random=105'
    }
  }
]

// 搜索
const onSearch = () => {
  showSearch.value = !showSearch.value
  if (!showSearch.value) {
    searchKeyword.value = ''
    loadCourses(true)
  }
}

const onSearchSubmit = () => {
  loadCourses(true)
}

const onSearchCancel = () => {
  showSearch.value = false
  searchKeyword.value = ''
  loadCourses(true)
}

// 分类切换
const onCategoryChange = () => {
  loadCourses(true)
}

// 加载课程列表
const loadCourses = async (reset = false) => {
  if (reset) {
    page.value = 1
    courseList.value = []
    finished.value = false
  }
  
  loading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    let filteredCourses = [...mockCourses]
    
    // 分类筛选
    if (activeCategory.value !== 'all') {
      const categoryMap = {
        frontend: '前端开发',
        backend: '后端开发',
        mobile: '移动开发',
        database: '数据库',
        ai: '人工智能'
      }
      filteredCourses = filteredCourses.filter(course => 
        course.category === categoryMap[activeCategory.value]
      )
    }
    
    // 搜索筛选
    if (searchKeyword.value) {
      filteredCourses = filteredCourses.filter(course =>
        course.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
        course.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
      )
    }
    
    // 难度筛选
    if (filterLevel.value !== 'all') {
      const levelMap = {
        beginner: '入门',
        intermediate: '进阶',
        advanced: '高级'
      }
      filteredCourses = filteredCourses.filter(course =>
        course.level === levelMap[filterLevel.value]
      )
    }
    
    // 价格筛选
    if (filterPrice.value !== 'all') {
      if (filterPrice.value === 'free') {
        filteredCourses = filteredCourses.filter(course => course.isFree)
      } else if (filterPrice.value === '0-100') {
        filteredCourses = filteredCourses.filter(course => !course.isFree && course.price <= 100)
      } else if (filterPrice.value === '100-500') {
        filteredCourses = filteredCourses.filter(course => !course.isFree && course.price > 100 && course.price <= 500)
      } else if (filterPrice.value === '500+') {
        filteredCourses = filteredCourses.filter(course => !course.isFree && course.price > 500)
      }
    }
    
    // 排序
    if (sortType.value === 'newest') {
      filteredCourses.sort((a, b) => new Date(b.updateTime) - new Date(a.updateTime))
    } else if (sortType.value === 'popular') {
      filteredCourses.sort((a, b) => b.studentCount - a.studentCount)
    } else if (sortType.value === 'rating') {
      filteredCourses.sort((a, b) => b.rating - a.rating)
    } else if (sortType.value === 'price_asc') {
      filteredCourses.sort((a, b) => a.price - b.price)
    } else if (sortType.value === 'price_desc') {
      filteredCourses.sort((a, b) => b.price - a.price)
    }
    
    // 分页
    const start = (page.value - 1) * pageSize
    const end = start + pageSize
    const newCourses = filteredCourses.slice(start, end)
    
    if (reset) {
      courseList.value = newCourses
    } else {
      courseList.value.push(...newCourses)
    }
    
    // 判断是否还有更多数据
    if (newCourses.length < pageSize || end >= filteredCourses.length) {
      finished.value = true
    }
    
    page.value++
  } catch (error) {
    showToast('加载失败')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  loadCourses(true)
}

// 上拉加载
const onLoad = () => {
  if (!finished.value) {
    loadCourses()
  }
}

// 课程点击
const onCourseClick = (course) => {
  router.push(`/course/${course.id}`)
}

// 页面初始化
onMounted(() => {
  loadCourses(true)
})
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
@import '@/styles/mixins.scss';

.courses {
  min-height: 100vh;
  background: $gray-50;
  padding-bottom: $tabbar-height;

  &__navbar {
    background: white;
    border-bottom: 1px solid $border-color;
  }

  &__search {
    background: white;
    padding: $spacing-xs $spacing-base;
    border-bottom: 1px solid $border-color;
  }

  &__filter {
    background: white;
    
    :deep(.van-tabs__nav) {
      background: white;
    }
    
    :deep(.van-tab) {
      font-size: $font-size-sm;
    }
  }

  &__toolbar {
    background: white;
    border-bottom: 1px solid $border-color;
  }

  &__content {
    flex: 1;
  }

  &__list {
    padding: $spacing-base;
  }
}

.course-card {
  background: white;
  border-radius: $border-radius-lg;
  margin-bottom: $spacing-base;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all $transition-duration-base;
  
  &:active {
    transform: scale(0.98);
  }

  &__cover {
    position: relative;
    height: 160px;
    overflow: hidden;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  &__badge {
    position: absolute;
    top: $spacing-xs;
    right: $spacing-xs;
  }

  &__free {
    background: $success-color;
    color: white;
    padding: $spacing-xs $spacing-sm;
    border-radius: $border-radius-base;
    font-size: $font-size-xs;
    font-weight: $font-weight-medium;
  }

  &__price {
    background: $primary-color;
    color: white;
    padding: $spacing-xs $spacing-sm;
    border-radius: $border-radius-base;
    font-size: $font-size-xs;
    font-weight: $font-weight-medium;
  }

  &__duration {
    position: absolute;
    bottom: $spacing-xs;
    right: $spacing-xs;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: $spacing-xs $spacing-sm;
    border-radius: $border-radius-base;
    font-size: $font-size-xs;
  }

  &__content {
    padding: $spacing-base;
  }

  &__title {
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    color: $text-color;
    margin: 0 0 $spacing-xs 0;
    @include text-ellipsis(2);
  }

  &__desc {
    font-size: $font-size-sm;
    color: $text-color-light;
    margin: 0 0 $spacing-base 0;
    @include text-ellipsis(2);
  }

  &__tags {
    display: flex;
    gap: $spacing-xs;
    margin-bottom: $spacing-base;
  }

  &__tag {
    padding: $spacing-xs $spacing-sm;
    border-radius: $border-radius-base;
    font-size: $font-size-xs;
    
    &--level {
      background: $warning-color;
      color: white;
    }
    
    &--category {
      background: $info-color;
      color: white;
    }
  }

  &__stats {
    display: flex;
    gap: $spacing-base;
    margin-bottom: $spacing-base;
  }

  &__stat {
    display: flex;
    align-items: center;
    gap: $spacing-xs;
    font-size: $font-size-xs;
    color: $text-color-light;
    
    .van-icon {
      color: $text-color-lighter;
    }
  }

  &__teacher {
    display: flex;
    align-items: center;
    gap: $spacing-xs;
    
    img {
      width: 24px;
      height: 24px;
      border-radius: 50%;
    }
    
    span {
      font-size: $font-size-sm;
      color: $text-color-light;
    }
  }
}

// 响应式适配
@include respond-below(480px) {
  .course-card {
    &__cover {
      height: 140px;
    }
    
    &__content {
      padding: $spacing-sm;
    }
    
    &__title {
      font-size: $font-size-base;
    }
  }
}
</style>